import api from '../request/api'

const tools = {
  /**
   * 获取商品单位数组
   * @param {String | Number} id 商品ID
   * @returns {Array} 商品单位数组
   */
  getUnit: async (id) => {
    const res = await api.source.goods.getdetail({ id, type: 1 })
    if (res.code == 200) {
      let unit = []
      if (res.data.more_unit == 1) {
        // 多单位
        unit = res.data.more_unit_data.unit_data
      } else {
        // 单一单位
        unit = [{ id: res.data.unit_id, name: res.data.unit_name }]
      }
      return unit
    }
  },

  /**
   * 获取设置是否开启
   * @param {String} name 设置名称
   * @returns {Boolean} 是否开启
   */
  getSet: async (name) => {
    const res = await api.set.index()
    if (res.code == 200) {
      const findRes = res.data.find(item => item.name == name)
      return findRes.is_checked == 1
    }
  },

  /**
   * 
   * @param {String} code 获取编号的type
   * @returns {String} 返回编号
   */
  getCode: async (code) => {
    const res = await api.common.getcode({ type: code })
    return res.data
  },
  /**
   * 成功 && 返回上一页
   */
  successBack: (msg) => {
    uni.showToast({
      title: msg,
      icon: 'none',
      mask: true
    })
    setTimeout(() => {
      uni.navigateBack({ delta: 1 })
    }, 600)
  },
  /**
   * 返回上一页(延时)
   */
  back: () => {
    setTimeout(() => {
      uni.navigateBack({ delta: 1 })
    }, 600)
  },
  /**
   * 填写完数据返回
   */
  goBack: () => {
    uni.navigateBack({ delta: 1 })
  },
  /**
   * toast
   */
  toast: (msg) => {
    uni.showToast({
      title: msg,
      icon: 'none',
    })
  },
  /**
   * 获取当前时间
   */
  getCurTime(type) {
    let Y = '',
      M = '',
      D = '',
      h = '',
      m = '',
      s = ''
    const date = new Date()
    Y = date.getFullYear()
    M = date.getMonth() + 1
    D = date.getDate()
    h = date.getHours()
    m = date.getMinutes()
    s = date.getSeconds()
    D = D < 10 ? ('0' + D) : D
    h = h < 10 ? ('0' + h) : h
    m = m < 10 ? ('0' + m) : m
    s = s < 10 ? ('0' + s) : s
    M = M < 10 ? ('0' + M) : M
    if (type == 1 || !type) {
      return Y + '-' + M + '-' + D
    } else if (type == 2) {
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
    }
  },
    /**
   * 转时间搓为年月日
   * 
   */
  timeRub: (time) => {
    let date2 = new Date(time)
    let year = date2.getFullYear()
    let month = date2.getMonth() + 1
    let day = date2.getDate()
   return time = year + '-' + month + '-' + day
  }
}

export default tools
